<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" min-width="100"></el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="150"></el-table-column>
        <el-table-column prop="mobile" label="电话" min-width="150"></el-table-column>
        <el-table-column prop="role_name" label="角色" min-width="150"></el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini">
              </el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 6, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" @close="addDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="addFormRef" :model="newUser" :rules="addUserRules" label-width="80px" label-position="right">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="newUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 编辑对话框: 内容主题区 -->
      <el-form ref="editFormRef" :model="editUser" :rules="addUserRules" label-width="80px" label-position="right">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <!-- 分配角色对话框: 内容主题区 -->
      <el-form ref="setRoleFormRef" label-width="88px" label-position="right">
        <div>
          <p>当前的用户:&nbsp; {{ userInfo.username }}</p>
          <p>当前的角色:&nbsp; {{ userInfo.role_name }}</p>
        </div>
        <el-form-item label="分配新角色:">
          <el-select v-model="rid" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRoleForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    // 验证email规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证phone规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      return callback(new Error('手机号码格式错误'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页数
        pagesize: 10 // 每页显示多少条数据
      },
      userList: [],
      total: 0,
      adddialogVisible: false, // 控制添加用户对话框的显示与隐藏
      editDialogVisible: false, // 控制编辑用户对话框的显示与隐藏
      setRoleDialogVisible: false, // 控制分配角色对话框的显示与隐藏
      // 添加用户的表单数据
      newUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUser: {},
      // 将要分配角色的用户信息
      userInfo: {},
      // 所有的角色列表
      roleList: [],
      // 选择的角色id
      rid: '',
      // 添加表单的验证规则对象
      addUserRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          },
          { whitespace: true, message: '不能为空格', trigger: 'blur' },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
            message: '只能输入汉字、字母、数字、下划线',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 16,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          },
          { whitespace: true, message: '不能为空格', trigger: 'blur' },
          {
            pattern: /^[A-Za-z0-9_]*$/,
            message: '只能输入数字、字母和下划线',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: 'emial不能为空', trigger: 'blur' },
          { whitespace: true, message: '不能为空格', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: 'mobile不能为空', trigger: 'blur' },
          { whitespace: true, message: '不能为空格', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听pagenum改变的事件
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum
      this.getUserList()
    },
    // 监听switch状态的改变
    async userStateChanged(user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
      }
    },
    // 监听对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 提交 "添加用户" 表单
    submitAddForm() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('users', this.newUser)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          this.adddialogVisible = false
          this.getUserList()
        }
      })
    },
    // 打开编辑用户对话框
    async showEditDialog(id) {
      // 根据id查询用户
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUser = res.data
      console.log('res.data: ', res.data)
      this.editDialogVisible = true
    },
    // 监听 "编辑用户" 对话框关闭事件
    editDialogClosed() {
      this.editUser = {}
    },
    // 提交用户编辑表单
    submitEditForm() {
      console.log('editUser: ', this.editUser)
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put('users/' + this.editUser.id, {
          id: this.editUser.id,
          email: this.editUser.email,
          mobile: this.editUser.mobile
        })
        console.log()
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 删除用户
    async deleteUser(user) {
      const result = await this.$messageBox
        .confirm('此操作将删除用户: ' + user.username + ', 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        .catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + user.id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    setRoleDialogClosed() {
      this.roleList = []
      this.userInfo = {}
      this.rid = ''
    },
    // 显示分配角色对话框
    async showSetRoleDialog(user) {
      // 1.当前用户信息
      this.userInfo = user
      // 2.查询所有角色信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(role => {
        this.roleList.push({
          id: role.id,
          roleName: role.roleName,
          roleDesc: role.roleDesc
        })
      })
      // 3. 显示对话框
      this.setRoleDialogVisible = true
    },
    // 给用户分配角色
    async submitSetRoleForm() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.rid
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRoleDialogVisible = false
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped></style>
